package com.rbac.admin.config;

import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.baomidou.mybatisplus.core.config.GlobalConfig;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.rbac.admin.utils.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * MyBatis Plus配置类
 * 
 * @author RBAC-Admin
 * @since 2024-01-01
 */
@Slf4j
@Configuration
public class MybatisPlusConfig {

    @Autowired
    private SnowflakeIdGenerator snowflakeIdGenerator;

    /**
     * MyBatis Plus 拦截器配置
     */
    @Bean
    public MybatisPlusInterceptor mybatisPlusInterceptor() {
        MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
        
        // 分页插件
        interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
        
        // 乐观锁插件
        interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
        
        // 防止全表更新与删除插件
        interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
        
        return interceptor;
    }

    /**
     * 自定义ID生成器
     */
    @Bean
    public IdentifierGenerator idGenerator() {
        return new IdentifierGenerator() {
            @Override
            public Long nextId(Object entity) {
                long id = snowflakeIdGenerator.nextId();
                log.debug("Generated snowflake ID: {} for entity: {}", id, entity.getClass().getSimpleName());
                return id;
            }

            @Override
            public String nextUUID(Object entity) {
                return snowflakeIdGenerator.nextIdStr();
            }
        };
    }

    /**
     * MyBatis Plus全局配置
     */
    @Bean
    public GlobalConfig globalConfig(IdentifierGenerator idGenerator) {
        GlobalConfig globalConfig = new GlobalConfig();
        globalConfig.setIdentifierGenerator(idGenerator);
        log.info("MyBatis Plus global config initialized with snowflake ID generator");
        return globalConfig;
    }
}